﻿using ProgressTracker.Data.Abstract;
using ProgressTracker.Domain.Contracts;
using ProgressTracker.Domain.Messages;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ProgressTracker.Domain.Services
{
    public class TaskService : ITaskService
    {
        private IDayRepository _dayRepo;
        private ITaskRepository _taskRepo;
        private IUserRepository _userRepo;

        public TaskService(
            IDayRepository dayRepo,
            ITaskRepository taskRepo,
            IUserRepository userRepo)
        {
            _dayRepo = dayRepo;
            _taskRepo = taskRepo;
            _userRepo = userRepo;
        }

        public void AddTask(AddTaskRequest request)
        {
            var user = _userRepo.GetUserByEmail(request.UserEmail);

            var taskToAdd = new Data.Entities.Task
            {
                Name = request.Name,
                Description = request.Description,
                User = user
            };

            _taskRepo.Add(taskToAdd);

            var day = _dayRepo.GetDay(DateTime.Today, request.UserEmail);

            if (day != null)
            {
                _dayRepo.AddTaskToDay(day, taskToAdd);
            }
        }

        public IEnumerable<Task> GetCurrentTasks(string userEmail)
        {
            var user = _userRepo.GetUserByEmail(userEmail);

            var tasks = _taskRepo.GetCurrentTasks(user.Id);

            //break out into mapper for testing later.
            return tasks.Select(x => new Task
                {
                    Description = x.Description,
                    Id = x.Id,
                    Name = x.Name
                });
        }

        public Task GetTask(int id)
        {
            var task = _taskRepo.GetTaskById(id);

            return new Task
            {
                Description = task.Description,
                Id = task.Id,
                Name = task.Name
            };
        }

        public void UpdateTask(UpdateTaskRequest request)
        {
            var taskToUpdate = _taskRepo.GetTaskById(request.Id);

            taskToUpdate.Name = request.Name;
            taskToUpdate.Description = request.Description;

            _taskRepo.Update(taskToUpdate);
        }

        public void DeleteTask(int id)
        {
            var task = _taskRepo.GetTaskById(id);

            _taskRepo.Delete(task);
        }

        public void ArchiveTask(int id)
        {
            var task = _taskRepo.GetTaskById(id);

            task.Archived = true;
            _taskRepo.Update(task);
        }
    }
}
